%{
    This file is part of StemCellQC, a video bioinformatics software
    toolkit for analysis of phase contrast microscopy videos.
    Copyright 2013-2015 Vincent On. [vincenton001-at-gmail.com]

    StemCellQC is free software: you can redistribute it and/or 
    modify it under the terms of the GNU General Public License as 
    published by the Free Software Foundation, either version 3 of the 
    License, or (at your option) any later version.

    StemCellQC is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with StemCellQC.  If not, see <http://www.gnu.org/licenses/>.
%}

function varargout = scqc_multi(varargin)
% SCQC_MULTI MATLAB code for scqc_multi.fig
%      SCQC_MULTI, by itself, creates a new SCQC_MULTI or raises the existing
%      singleton*.
%
%      H = SCQC_MULTI returns the handle to a new SCQC_MULTI or the handle to
%      the existing singleton*.
%
%      SCQC_MULTI('CALLBACK',hObject,eventData,handles,...) calls the local
%      function named CALLBACK in SCQC_MULTI.M with the given input arguments.
%
%      SCQC_MULTI('Property','Value',...) creates a new SCQC_MULTI or raises the
%      existing singleton*.  Starting from the left, property value pairs are
%      applied to the GUI before scqc_multi_OpeningFcn gets called.  An
%      unrecognized property name or invalid value makes property application
%      stop.  All inputs are passed to scqc_multi_OpeningFcn via varargin.
%
%      *See GUI Options on GUIDE's Tools menu.  Choose "GUI allows only one
%      instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES

% Edit the above text to modify the response to help scqc_multi

% Last Modified by GUIDE v2.5 07-Jul-2015 11:59:32

% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
    'gui_Singleton',  gui_Singleton, ...
    'gui_OpeningFcn', @scqc_multi_OpeningFcn, ...
    'gui_OutputFcn',  @scqc_multi_OutputFcn, ...
    'gui_LayoutFcn',  [] , ...
    'gui_Callback',   []);
if nargin && ischar(varargin{1})
    gui_State.gui_Callback = str2func(varargin{1});
end

if nargout
    [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
    gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT


% --- Executes just before scqc_multi is made visible.
function scqc_multi_OpeningFcn(hObject, eventdata, handles, varargin)
global mov
handles.output = hObject;
handles.main_gui = hObject;
guidata(hObject, handles);

% initialization
mov = [];
addpath( cd );
set( handles.edit1, 'String', '1' );
% This is the previous path
set( handles.m_fileOpenMov, 'UserData', cd );

% --- Outputs from this function are returned to the command line.
function varargout = scqc_multi_OutputFcn(hObject, eventdata, handles)
% varargout  cell array for returning output args (see VARARGOUT);
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Get default command line output from handles structure
varargout{1} = handles.output;

%% Menu funtions

% --------------------------------------------------------------------
function m_file_Callback(hObject, eventdata, handles)
% hObject    handle to m_file (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)


%{
Callback function for opening a movie file.
%}
function m_fileOpenMov_Callback(hObject, eventdata, handles)
global mov
global features

track_multi = get( handles.Multiple_box, 'value' );
struct_multiplier = str2double( get( handles.struct_el_mult, 'String' ) );
seg_method = get( handles.segment_menu, 'value' );
fudgeFactor = str2double( get( handles.fudge_factor_edit, 'String' ) );

[file, path] = uigetfile( ...
    [ get( handles.m_fileOpenMov, 'UserData' ) '\*.*'], ...
    'Load Video' );
set( handles.m_fileOpenMov, 'UserData', path );

try
    switch track_multi
        case 0
            hWaitbar = waitbar( 0, 'Loading image 0' );
            [mov, k] = fun_loadVideo( file, path );
            
            skip_frame = 0;
            for i=1:size(mov,2)
                if skip_frame == 0
                    skip_frame = fun_automate( i , seg_method, struct_multiplier, skip_frame, fudgeFactor );
                    
                elseif skip_frame == 1
                    skip_frame = fun_automate( i , seg_method, struct_multiplier, skip_frame, fudgeFactor );
                    
                    if skip_frame == 0
                        fix_skipped_frame( i );
                    end
                elseif skip_frame > 1
                    errordlg('Too many skipped frames','Bad Segmentation');
                    break
                end
                
                close( hWaitbar );
                hWaitbar = waitbar( i / size(mov,2), ...
                    [ 'Loading image ' num2str(i) ] );
            end
            close( hWaitbar );
            
            feat_out()
            
            imshow( mov(k).original, 'Parent', handles.axes1 );
            set( handles.text3, 'String', [ 'Total Frames: ' num2str( k ) ] );
            set( handles.edit1, 'String', num2str(k) );
            msgbox( [ file ' loaded (' num2str(k) ' frames total).' ] );
    
        case 1
            min_seg_area = str2double( get( handles.Min_area_edit, 'String' ) );
            max_move = str2double( get( handles.max_move_edit, 'String' ) );
            
            hWaitbar = waitbar( 0, 'Loading image 0' );
            [mov, k] = fun_loadVideo( file, path );
            
            %extract all objects greater than minimum size
            for i=1:size(mov,2)
                close( hWaitbar );
                hWaitbar = waitbar( i / size(mov,2), ...
                [ 'Loading image ' num2str(i) ] );
            
                switch seg_method
                    case 1
                        fun_segment_multi(  i , struct_multiplier, min_seg_area ); 
                    case 2
                        fun_segment_multi_edge( i, min_seg_area, fudgeFactor );
                end
            end
            
            close( hWaitbar );
            hWaitbar = waitbar( 0, 'Creating tracks' );
            %create links of between connected components in adjacent
            %frames
            cc = cell(1);
            cc_link = cell(1);
            
            cc{1} = bwconncomp(mov(1).segmented);
            for i = 2 : length( mov )
                cc{ i } = bwconncomp(mov(i).segmented);
                cc_link{ i - 1 } = connect_cc( cc{ 1, i - 1 }, cc{ 1, i }, max_move );
            end
            
            %create tracks from links
            tracks = connect_tracklet(cc_link, cc);
            
            
            
            %update handles
            handles.tracks = tracks;
            handles.cc = cc;
            guidata(hObject, handles);
         
            %update table with track information
            tracks_table = tracks2cell( tracks );
            track_fields = fieldnames( tracks );
            track_fields{1} = 'Frames';
            
            set( handles.tracks_table, 'data', tracks_table, 'ColumnName', track_fields );
            
            %select tracks
            select_track = get( handles.select_tracks_checkbox, 'value' );
            close( hWaitbar );
            
            switch select_track
                case 0
                    selected = 1:length( tracks );
                case 1
                    hWaitbar = waitbar( 0, 'Select tracks then click continue' );
                    uiwait(handles.output); %pause so that user may select tracks, uiresume with continue button

                    selected = get( handles.track_select_edit, 'String' );
                    selected = eval(['[' selected ']']);  
                    if ishandle( hWaitbar )
                        close( hWaitbar );
                    end
            end

            for i = selected
                frame = tracks(i).start_frame;
                hWaitbar = waitbar( 0, [ 'Extracting track ' num2str(i) '/' num2str( numel( tracks ))]);
                
                if isfield( mov, 'features')
                    mov = rmfield(mov, 'features');
                end
                
                skip_frame = 0;
                for j = 1 : length(tracks(i).cc_label)
                    close( hWaitbar );
                    hWaitbar = waitbar( j / length( tracks( i ).cc_label ), ...
                        [ 'Extracting track ' num2str( i ) '/' num2str( numel( tracks ))]);
                    temp = zeros( size( mov( j ).segmented ));
                    idx = tracks( i ).cc_label( j );
                    temp( cc{ frame }.PixelIdxList{ idx }) = 1;
                    
                    if skip_frame == 0
                        skip_frame = fun_automate_multi( frame, temp, skip_frame );
                        
                    elseif skip_frame == 1
                        skip_frame = fun_automate_multi( frame, temp, skip_frame );
                        
                        if skip_frame == 0
                            fix_skipped_frame( frame );
                        end
                    elseif skip_frame > 1
                        errordlg( 'Too many skipped frames' , 'Bad Segmentation' );
                        break
                    end
                    
%                     skip_frame = fun_automate_multi( frame, temp, 0 );
                    
                    frame = frame + 1;
                end
                close( hWaitbar );
                features = [];
                feat_out()
                
                %save excel file
                try
                    xlsname = strsplit( file );
                    [~,~,ext] = fileparts(xlsname{1});
                    xlsname = regexprep(xlsname{1}, ext, '' );
                    cell2csv( [ path '\' xlsname '_track' num2str(i) '.csv' ], features, ',' )
                catch e
                    errordlg( e.message, e.identifier );
                end
            end
            
            imshow( mov(k).original, 'Parent', handles.axes1 );
            set( handles.text3, 'String', [ 'Total Frames: ' num2str( k ) ] );
            set( handles.edit1, 'String', num2str(k) );
            msgbox( [ file ' loaded (' num2str(k) ' frames total).' ] );
    end
    
    guidata(hObject, handles);
catch e
    errordlg( e.message, e.identifier );
    set( handles.m_fileOpenMov, 'UserData', cd );
end

% --------------------------------------------------------------------
function m_openIm_Callback(hObject, eventdata, handles)
% hObject    handle to m_openIm (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

%{
    Internal function to see if MOV exists
%}
function res = movExists()
global mov

if ~exist( 'mov' )
    mov = [];
end

%{
    Callback for them adding an entire folder of images MOV
%}
function m_fileOpenFolder_Callback(hObject, eventdata, handles)
global mov
movExists % obligatory check to make sure mov exists
seg_method = get( handles.segment_menu, 'value' );
struct_multiplier = str2double( get( handles.struct_el_mult, 'String' ) );
fudgeFactor = str2double( get( handles.fudge_factor_edit, 'String' ) );
try 
    % get the directory
    folder_name = uigetdir;
    pastDir = cd;
    cd( folder_name );
    
    % the list of files in the directory
    list = ls;
    
    % remove '.' and '..' from list
    index = find(list(:,1)=='.');
    list(index, : ) = [];
    
    
    oldm = size( mov, 2 );
    
    hWaitbar = waitbar( 0, 'Loading image 0' );
    skip_frame = 0;
    for i=1:size(list,1)
        m = size( mov, 2 );
        display( deblank( list(i,:) ) ) ;
        
        temp = imread( deblank( list(i,:) ) );
        
        
        mov(m+1).original = temp;
        
        if size( temp, 3 ) > 1
            mov(m+1).data = rgb2gray( temp );
        else
            mov(m+1).data = temp;
        end
        
        mov(m+1).file = deblank( list(i,:) );
        
        
        fun_automate( m+1 , seg_method, struct_multiplier, skip_frame, fudgeFactor );
        
        if skip_frame == 0
            skip_frame = fun_automate( m+1 , seg_method, struct_multiplier, skip_frame, fudgeFactor );
            
        elseif skip_frame == 1
            skip_frame = fun_automate( m+1 , seg_method, struct_multiplier, skip_frame, fudgeFactor );
            
            if skip_frame == 0
                
                fix_skipped_frame( m+1 );
            end
        elseif skip_frame > 1
            errordlg('Too many skipped frames','Bad Segmentation');
            break
        end
        
        close( hWaitbar );
        hWaitbar = waitbar( i / size(mov,2), ...
            [ 'Loading image ' num2str(i) ]  );
    end
    close( hWaitbar );
    
    imshow( mov(m+1).original, 'Parent', handles.axes1 );
    set( handles.text3, 'String', [ 'Total Frames: ' num2str( m+1 ) ] );
    set( handles.edit1, 'String', num2str(m+1) );
    msgbox( [ folder_name ' loaded (' num2str(size( mov, 2 ) - oldm) ' new frames total).' ] );
catch e
    errordlg( e.message, e.identifier );
end

cd( pastDir );


% --------------------------------------------------------------------
%function loads folder of videos, extracts each video and save features to
%excel file with same name as video.  Also saves .mat file of workspace
%with the same name as video
function m_fileFolderMov_Callback(hObject, eventdata, handles)
% hObject    handle to m_fileFolderMov (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

global mov
global features
seg_method = get( handles.segment_menu, 'value' );
struct_multiplier = str2double( get( handles.struct_el_mult, 'String' ) );
fudgeFactor = str2double( get( handles.fudge_factor_edit, 'String' ) );

folder_name = uigetdir;
pastDir = cd;
cd( folder_name );
path = cd;

% the list of files in the directory
list = ls;

% remove '.' and '..' from list
index = find(list(:,1)=='.');
list(index, : ) = [];

cd( pastDir );
%extract features from video
for j = 1 : size(list,1)
    try
        hWaitbar = waitbar( 0, ['Loading image 0 - Video ' num2str(j)]);
        file = list(j,:);
        [mov, k] = fun_loadVideo( file, path );
        
        
        skip_frame = 0;
        for i=1:size(mov,2)
            
        
        if skip_frame == 0
            skip_frame = fun_automate( i , seg_method, struct_multiplier, skip_frame, fudgeFactor );
            
        elseif skip_frame == 1
            skip_frame = fun_automate( i , seg_method, struct_multiplier, skip_frame, fudgeFactor );
            
            if skip_frame == 0
                fix_skipped_frame( i );
            end
        elseif skip_frame > 1
            errordlg('Too many skipped frames','Bad Segmentation');
            break
        end
        
        close( hWaitbar );
        hWaitbar = waitbar( i / size(mov,2), ...
            [ 'Loading image ' num2str(i) ' - Video ' num2str(j) ] );
    end
        close( hWaitbar );
        
        features = [];
        feat_out()
        
        imshow( mov(k).original, 'Parent', handles.axes1 );
        set( handles.text3, 'String', [ 'Total Frames: ' num2str( k ) ] );
        set( handles.edit1, 'String', num2str(k) );
        msgbox( [ file ' loaded (' num2str(k) ' frames total).' ] );
    catch e
        errordlg( e.message, e.identifier );
        set( handles.m_fileOpenMov, 'UserData', cd );
    end
    
    %save excel file
    try
        
        [~,~,ext] = fileparts(file);
        xlsname = regexprep(file, ext, '' );
        cell2csv( [ path '\' xlsname '.csv' ], features, ',' )
    catch e
        errordlg( e.message, e.identifier );
    end
    xlswrite( 'results.xls', features );
    %save( [ path '\' file '.mat'], 'mov' );
    figure;
    imshow( mov(end).segmented )
    title([ 'Last Segmented Frame - Video ' num2str(j) ' - ' file])
    
    figure;
    imshow( mov(end).original )
    title([ 'Last Frame - Video ' num2str(j) ' - ' file])
    
    
end

%{
    Callback for them adding a single frame to MOV
%}
function m_fileOpenFrame_Callback(hObject, eventdata, handles)
global mov
mov = [];
movExists % obligatory check to make sure mov exists
seg_method = get( handles.segment_menu, 'value' );
struct_multiplier = str2double( get( handles.struct_el_mult, 'String' ) );
fudgeFactor = str2double( get( handles.fudge_factor_edit, 'String' ) );
try 
    m = size( mov, 2 );
    
    %get the file, leave it open
    [file, path] = uigetfile( ...
        [ get( handles.m_fileOpenMov, 'UserData' ) '\*.*'], ...
        'Load Image' );
    set( handles.m_fileOpenMov, 'UserData', path );
    
    temp = imread( [ path '\' file ] );
    
    mov(m+1).original = temp;
    
    if size( temp, 3 ) > 1
        mov(m+1).data = rgb2gray( temp );
    else
        mov(m+1).data = temp;
    end
    
    mov(m+1).file = [ path '\' file ];
    
    fun_automate( m+1, seg_method, struct_multiplier, 0, fudgeFactor );
    
    imshow( mov(m+1).original, 'Parent', handles.axes1 );
    set( handles.text3, 'String', [ 'Total Frames: ' num2str( m+1 ) ] );
    set( handles.edit1, 'String', num2str(m+1) );
    msgbox( [ file ' loaded.' ] );
catch e
    errordlg( e.message, e.identifier );
    set( handles.m_fileOpenMov, 'UserData', cd );
end

% --------------------------------------------------------------------
function m_fileSaveWorkspace_Callback(hObject, eventdata, handles)
% hObject    handle to m_fileSaveWorkspace (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

global mov


try
    [file,path] = uiputfile('Untitled.mat','Save Data As');
    save( [ path '\' file ], 'mov','-v7.3' );
catch e
    errordlg( e.message, e.identifier );
end




% --------------------------------------------------------------------
function m_fileLoadWorkspace_Callback(hObject, eventdata, handles)
% hObject    handle to m_fileLoadWorkspace (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

global mov
mov = [];

[file, path] = uigetfile('*.mat*','Load .mat File of Previous Segementation');

load([ path '\' file ]);

% imshow( mov(1).original, 'Parent', handles.axes1 );
% set( handles.text3, 'String', [ 'Total Frames: ' num2str( 1 ) ] );
% set( handles.edit1, 'String', num2str(1) );
msgbox( 'Loaded Previous Segmentation' )





% --------------------------------------------------------------------
function m_help_Callback(hObject, eventdata, handles)
% hObject    handle to m_help (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)


% --------------------------------------------------------------------
function m_helpBreak_Callback(hObject, eventdata, handles)

msgbox( ...
    sprintf('This file is part of StemCellQC, a video bioinformatics software toolkit for analysis of phase contrast microscopy videos.  Copyright 2013-2015. \n \n StemCellQC is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.\n \n StemCellQC is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more details.\n \n You should have received a copy of the GNU General Public License along with StemCellQC. If not, see <http://www.gnu.org/licenses/>.\n' ) );

%% 


% --------------------------------------------------------------------

%{
    Edit 1 is used to preview frames
%}
function edit1_Callback(hObject, eventdata, handles)
global mov

% Hints: get(hObject,'String') returns contents of edit1 as text
%        str2double(get(hObject,'String')) returns contents of edit1 as a double
num = str2double(get(hObject,'String'));

try
    
scqc_plot_update

catch e
    errordlg( e.message, e.identifier );
    set( hObject, 'String', 'Error' );
end


% --- Executes during object creation, after setting all properties.
function edit1_CreateFcn(hObject, eventdata, handles)
% hObject    handle to edit1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


%{
    Used to clear MOV
%}
function m_fileNew_Callback(hObject, eventdata, handles)
global mov
set( handles.text3, 'String', [ 'Total Frames: 0' ] );
set( handles.edit1, 'String', num2str(0) );
mov = [];


% Quits
function m_fileQuit_Callback(hObject, eventdata, handles)
close(gcf); 


%{
    Callback for messing with the slider
%}
function popupmenu1_Callback(hObject, eventdata, handles)
global mov

num = str2double(get(handles.edit1,'String'));

try
    
    scqc_plot_update
    
catch e
    errordlg( e.message, e.identifier );
    set( handles.edit1, 'String', 'Error' );
end


% --- Executes during object creation, after setting all properties.
function popupmenu1_CreateFcn(hObject, eventdata, handles)
% hObject    handle to popupmenu1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: popupmenu controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

%{
    This is the save function
%}
function m_fileSave_Callback(hObject, eventdata, handles)
global mov
global features

try
    [file,path] = uiputfile('Untitled.csv','Save Data As');
    cell2csv( [ path '\' file ], features, ',' )
catch e
    errordlg( e.message, e.identifier );
end
xlswrite( 'results.xls', features );


function pushRev_Callback(hObject, eventdata, handles)
pushFrame( -1, handles )

function pushFow_Callback(hObject, eventdata, handles)
pushFrame( 1, handles )

function pushFrame( step, handles )
global mov

n = str2double( get( handles.edit1, 'String' ) );
num = n + step;

if num > 0 && num <= size(mov,2)
    set( handles.edit1, 'UserData', num );
    set( handles.edit1, 'String', num2str( num ) );
%     if val == 1
%         imshow( mov( adjN ).original, [], 'Parent',  handles.axes1 );
%     else
%         imshow( mov( adjN ).segmented, [], 'Parent',  handles.axes1 );
%     end

    scqc_plot_update
end


% --- Executes during object creation, after setting all properties.
function axes1_CreateFcn(hObject, eventdata, handles)
% hObject    handle to axes1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: place code in OpeningFcn to populate axes1

%% GUI Toolbox

% --------------------------------------------------------------------
function m_tools_Callback(hObject, eventdata, handles)
% hObject    handle to m_tools (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)


% --------------------------------------------------------------------
function m_classifier_Callback(hObject, eventdata, handles)
% hObject    handle to m_classifier (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
Classify_samples_gui

% --------------------------------------------------------------------
function m_build_classifier_Callback(hObject, eventdata, handles)
% hObject    handle to m_build_classifier (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
classifier_gui
    
% --------------------------------------------------------------------
function m_plot_feats_Callback(hObject, eventdata, handles)
% hObject    handle to m_plot_feats (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
plot_gui

% --------------------------------------------------------------------
function m_mod_xls_Callback(hObject, eventdata, handles)
% hObject    handle to m_mod_xls (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
mod_xls_gui

% --------------------------------------------------------------------
function m_patch_bio_Callback(hObject, eventdata, handles)
% hObject    handle to m_patch_bio (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
Patch_gui

% --------------------------------------------------------------------
function m_overlay_Callback(hObject, eventdata, handles)
% hObject    handle to m_overlay (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
overlay_videos_gui

%%


function struct_el_mult_Callback(hObject, eventdata, handles)
% hObject    handle to struct_el_mult (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of struct_el_mult as text
%        str2double(get(hObject,'String')) returns contents of struct_el_mult as a double


% --- Executes during object creation, after setting all properties.
function struct_el_mult_CreateFcn(hObject, eventdata, handles)
% hObject    handle to struct_el_mult (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


% --- Executes on button press in Multiple_box.
function Multiple_box_Callback(hObject, eventdata, handles)
% hObject    handle to Multiple_box (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of Multiple_box



function Min_area_edit_Callback(hObject, eventdata, handles)
% hObject    handle to Min_area_edit (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of Min_area_edit as text
%        str2double(get(hObject,'String')) returns contents of Min_area_edit as a double


% --- Executes during object creation, after setting all properties.
function Min_area_edit_CreateFcn(hObject, eventdata, handles)
% hObject    handle to Min_area_edit (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end



function track_edit_Callback(hObject, eventdata, handles)
% hObject    handle to track_edit (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of track_edit as text
%        str2double(get(hObject,'String')) returns contents of track_edit as a double

global mov
num = str2double(get( handles.edit1 ,'String'));

try
    
scqc_plot_update

catch e
    errordlg( e.message, e.identifier );
    set( hObject, 'String', 'Error' );
end


% --- Executes during object creation, after setting all properties.
function track_edit_CreateFcn(hObject, eventdata, handles)
% hObject    handle to track_edit (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


% --- Executes on button press in track_for_push.
function track_for_push_Callback(hObject, eventdata, handles)
% hObject    handle to track_for_push (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
pushTrack( 1, handles )


% --- Executes on button press in track_rev_push.
function track_rev_push_Callback(hObject, eventdata, handles)
% hObject    handle to track_rev_push (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
pushTrack( -1, handles )

function pushTrack( step, handles )
global mov

n = str2double( get( handles.track_edit, 'String' ) );
track_num = n + step;
num = str2double(get( handles.edit1 ,'String'));

if isfield(handles,'tracks')
    tracks = handles.tracks;
else
    tracks = 1;
end

if track_num > 0 && track_num <= numel(tracks)
    set( handles.track_edit, 'UserData', track_num );
    set( handles.track_edit, 'String', num2str( track_num ) );

    scqc_plot_update
end



function max_move_edit_Callback(hObject, eventdata, handles)
% hObject    handle to max_move_edit (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of max_move_edit as text
%        str2double(get(hObject,'String')) returns contents of max_move_edit as a double


% --- Executes during object creation, after setting all properties.
function max_move_edit_CreateFcn(hObject, eventdata, handles)
% hObject    handle to max_move_edit (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


% --- Executes on button press in edge_d_box.
function edge_d_box_Callback(hObject, eventdata, handles)
% hObject    handle to edge_d_box (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of edge_d_box


% --- Executes on button press in otsu_box.
function otsu_box_Callback(hObject, eventdata, handles)
% hObject    handle to otsu_box (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of otsu_box


% --- Executes on selection change in segment_menu.
function segment_menu_Callback(hObject, eventdata, handles)
% hObject    handle to segment_menu (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: contents = cellstr(get(hObject,'String')) returns segment_menu contents as cell array
%        contents{get(hObject,'Value')} returns selected item from segment_menu


% --- Executes during object creation, after setting all properties.
function segment_menu_CreateFcn(hObject, eventdata, handles)
% hObject    handle to segment_menu (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: popupmenu controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end



function track_select_edit_Callback(hObject, eventdata, handles)
% hObject    handle to track_select_edit (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of track_select_edit as text
%        str2double(get(hObject,'String')) returns contents of track_select_edit as a double


% --- Executes during object creation, after setting all properties.
function track_select_edit_CreateFcn(hObject, eventdata, handles)
% hObject    handle to track_select_edit (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


% --- Executes on button press in continue_button.
function continue_button_Callback(hObject, eventdata, handles)
% hObject    handle to continue_button (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
uiresume(handles.main_gui);


% --- Executes on button press in select_tracks_checkbox.
function select_tracks_checkbox_Callback(hObject, eventdata, handles)
% hObject    handle to select_tracks_checkbox (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of select_tracks_checkbox



function fudge_factor_edit_Callback(hObject, eventdata, handles)
% hObject    handle to fudge_factor_edit (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of fudge_factor_edit as text
%        str2double(get(hObject,'String')) returns contents of fudge_factor_edit as a double


% --- Executes during object creation, after setting all properties.
function fudge_factor_edit_CreateFcn(hObject, eventdata, handles)
% hObject    handle to fudge_factor_edit (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end
